package com.wu.webflux6.sms;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authentication.ServerFormLoginAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

@Component
public class SmsAuthenticationConverter extends ServerFormLoginAuthenticationConverter {

	private String parameter1 = "phone";

	private String parameter2 = "smscode";

	@Override
	public Mono<Authentication> convert(ServerWebExchange exchange) {

		// TODO 验证手机号，验证码(不好做，放入token，在后边验证吧)
//		String phone = exchange.getSession().block().getAttribute("phone");
//		String smscode = exchange.getSession().block().getAttribute("smscode");
//		Object createTime = exchange.getSession().block().getAttribute("createTime");

		Map<String, String> concurrentHashMap = new ConcurrentHashMap<>();

		exchange.getSession().map(se -> {
			String phone = se.getAttribute("phone");
			String smscode = se.getAttribute("smscode");
			Object createTime = se.getAttribute("createTime");
			concurrentHashMap.put("phone", phone);
			concurrentHashMap.put("smscode", smscode);
			concurrentHashMap.put("createTime", String.valueOf(createTime));
			return Mono.just(concurrentHashMap);
		}).subscribe(System.out::println);

		return exchange.getFormData().map(data -> {
			String dataParameter1 = data.getFirst(this.parameter1);
			String dataParameter2 = data.getFirst(this.parameter2);
			return new SmsCodeAuthenticationToken(dataParameter1, dataParameter2, concurrentHashMap);

		});
	}

}
